package com.pig4cloud.pigx.common.customize.api.interceptor;

import com.pig4cloud.pigx.common.customize.api.annotation.OpenApi;
import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * {@link OpenApi} 配套拦截器
 *
 * @since 2022/11/11 15:12
 */
@Component
@AllArgsConstructor
public class OpenApiInterceptor implements HandlerInterceptor {

	/**
	 * 控制器方法执行之前
	 *
	 * @param request  请求包
	 * @param response 相应包
	 * @param handler  控制器方法
	 * @return {@link boolean}
	 * @since 2022/11/11 15:26
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		if (!(handler instanceof HandlerMethod)) {
			// 服务器内部错误
			OpenApiUtil.throwError(AbnormalEnum.MSG.DISCONNECTED);
		}

		HandlerMethod method = (HandlerMethod) handler;
		// 获取OpenApi注解
		OpenApi openApi = OpenApiValidator.getOpenApi(method);
		// 为空直接放行
		if (Objects.isNull(openApi)) {
			return true;
		}

		// 构建校验器
		OpenApiValidator.build(openApi, request, response)
				// 处理访问频率
				.handleRateLimit()
				// 判断请求时间戳
				.handleServerTime()
				// 判断权限
				.handlePermission()
				// 如果需要验证签名，验证签名
				.handleSignature();

		return true;
	}
}
